<?php
/**
ShopEx licence
*
* @copyright  Copyright (c) 2005-2013 ShopEx Technologies Inc. (http://www.shopex.cn)
* @license  http://ecos.shopex.cn/ ShopEx License
 */

class wxapi_ctl_goods extends wxapi_response{
    public $pagedata;
    public function __construct(&$app) {
        parent::__construct($app);
    }

    /*
     * 查询商品列表
     *
     * @params array $gids 搜索到到的商品ID集合
     * @params array $goodsData 搜索到的商品数据
     * @return array
     * */
    public function searchGoodsList()
    {
        $tagId = $_GET['tagId'] ? $_GET['tagId'] : '';
        if($tagId == 'undefined'){
            $tagId = '';
        }
        $cat_id = '';
        $sales = intval($_GET['sales']) ;
        $params['page'] = isset($_GET['page']) ? $_GET['page'] : 1;
        $params['size'] = isset($_GET['size']) ? $_GET['size'] : 10;
        $page_size = $params['size'];
        if($_GET['cateCode'] && $_GET['cateCode'] != 'undefined'){
            $cat_id = explode(',',$_GET['cateCode']);
        }
        $params['scontent'] = $_GET['searchKeyWords'];
        $sort = $_GET['sort'];//排序 3,销量，2,价格降序 1,价格升序
        if( isset($_GET['brand_id']) ){
            $params['brand_id'] = intval($_GET['brand_id']);
        }
        
        $total_count = 0;
        $total_page = 0;
        if( $sales==1 ){
            $goodsPmtModel = app::get('b2c')->model('goods_pmt');
            $total_count = $goodsPmtModel->count();
            $total_page = ceil($total_count / $params['size']);
            $goodsPmtOrder = 'goods_id desc';
            if($sort == 1){
                $goodsPmtOrder = 'price desc';
            }elseif ($sort == 2){
                $goodsPmtOrder = 'price asc';
            }
            $salesLsit = $goodsPmtModel->getList('goods_id', array(),($params['page'] -1) *$params['size'], $page_size,$goodsPmtOrder);
             $params['goods_id|in'] = array_column($salesLsit,'goods_id');
        }
        
        if($tagId){
            $params['gTag'] = explode(',',$tagId);
        }
        switch ($sort){
            case 1:
                $params['orderBy'] = "price desc";
                break;
            case 2:
                $params['orderBy'] = "price asc";
                break;
            case 3:
                $params['orderBy'] = "buy_w_count asc";
        }
        $params = $this->_filter_decode($params, $cat_id);
        $page = $params['page'];
        $this->pagedata['filter'] = $params['params'];
        if( $sales==1 ){
            $page = 1;
        }
        $goodsData = $this->_get_goods($params['filter'], $page, $params['orderby'], $page_size);
        //self::return_json($params);
        $goodslist = array();
        if(!empty($goodsData)){
            //self::return_json($goodsData);
            foreach ($goodsData as  $key => $val){
                
                $thumLogo = $val['thumbnail_pic'] ? $val['thumbnail_pic'] : $val['image_default_id'];               
                $smallProgramImage = $val['small_program_image'] ? $val['small_program_image'] : $thumLogo;
                
                $thumLogo = base_storager::image_path($thumLogo,'m');
                $smallProgramImage = base_storager::image_path($smallProgramImage,'m');
                
                $goodslist[$key]['marketPrice'] =       round($val['mktprice'],2);
                $goodslist[$key]['code'] =              $val['bn'];
                $goodslist[$key]['saleCount'] =         $val['buy_count'];
                $goodslist[$key]['businessId'] =        $val['goods_id'];
                $goodslist[$key]['businessName'] =      $val['name'];
                $goodslist[$key]['thumLogo'] =          $thumLogo;
                $goodslist[$key]['smallProgramImage']=  $smallProgramImage;
                $goodslist[$key]['evaluateCount'] =     $val['comments_count'];
                $goodslist[$key]['price'] =              round($val['price'],2);
                $goodslist[$key]['name'] =              $val['name'];
                $goodslist[$key]['stockNum'] =          $val['store'];
                $goodslist[$key]['logo'] =              base_storager::image_path($val['image_default_id']);
                $goodslist[$key]['id'] =                $val['goods_id'];
                $goodslist[$key]['sourceFlag'] =        '';
                $goodslist[$key]['status'] =            $val['disabled'] == 'true' ? 1 : 0;
            }
        }
        $screen = $this->screen($cat_id,$params['filter']);
        $screenArr = array();
        if (!empty($screen)){
            foreach ($screen as $key => $value){
                //$screenArr[$key]['cat']['data'] = $value['cat'];
                //$screenArr[$key]['cat']['name'] = '分类';
                $screenArr[$key]['brand']['data'] = $value['brand'];
                $screenArr[$key]['brand']['name'] = '品牌';
                /*
                if($value['spec']){
                    foreach ($value['spec'] as $val){
                        if (!empty($val['spec_value'])){
                            foreach ($val['spec_value'] as &$v){
                                if(!empty($v['spec_image'])){
                                    $v['spec_image'] = base_storager::image_path($v['spec_image']);
                                }
                            }
                        }
                        $screenArr[$key][$val['spec_type']]['data'] = $val['spec_value'];
                        $screenArr[$key][$val['spec_type']]['name'] = $val['name'];
                    }
                    break;
                }*/
            }
        }
        
        if($total_count && $total_page){
            $page_total = $total_page;
            $totalCount = $total_count;
        } else {
            $page_total = ceil($this->pagedata["total"]/$this->pagedata["pageLimit"]);
            $totalCount = $this->pagedata["total"] ? $this->pagedata["total"] : 0;
        }
        
        $api_data = array(
            'screen'=>$screenArr,
            'reason' =>         '',
            'code' =>           0,//返回大于0表示错误
            'page_total' =>     $page_total,
            'pageSize' =>       $this->pagedata["pageLimit"],
            'list' =>           $goodslist,
            'totalCount' =>     $totalCount,
            'pageNum' =>        $params['page'],
        );
        self::return_json($api_data);
    }
    
    /*
     * 返回搜索条件
     *
     * @params array $params 已有条件
     * @params int   $cat_id 分类ID
     * @params nit   $virtual_cat_id 虚拟分类ID
     * @return array
     */
    private function _filter_decode($params, $cat_id,$virtual_cat_id=null){
        if($virtual_cat_id){
            $params['virtual_cat_id']  = $virtual_cat_id;
        }
        $filter['params'] = $params;
        #分类
        $params['cat_id'] = $cat_id ? $cat_id : $params['cat_id'];
        if(!$params['cat_id']) unset($params['cat_id']);
        if($params['search_keywords'][0]){
            $params['orderBy'] = $params['orderBy'] ? $params['orderBy'] : 'view_count desc';
        }elseif($params['scontent']){
            $params['scontent'] = 'n,'.$params['scontent'];
            $oSearch = app::get('b2c')->model('search');
            $decode = $oSearch->decode($params['scontent']);
            $params['search_keywords'] = $decode['search_keywords'];
            unset($params['scontent']);
        }

        if($params['search_keywords']){
            $params['search_keywords']= str_replace('%xia%','_',$params['search_keywords']);
        }

        #排序
        $orderby = $params['orderBy'];unset($params['orderBy']);

        #分页,页码
        $page= $params['page'];unset($params['page']);

        #商品显示方式
        if($params['showtype']){
            $showtype = $params['showtype'];unset($params['showtype']);
        }else{
            $showtype = app::get('b2c')->getConf('gallery.default_view');
        }

        $params['marketable'] = 'true';
        $params['is_buildexcerpts'] = 'true';
        $tmp_filter = $params;

        #价格区间筛选
        if($tmp_filter['price']){
            $tmp_filter['price'] = explode('~',$tmp_filter['price'][0]);
        }
        #商品标签筛选条件
        if($tmp_filter['gTag']){
            $tmp_filter['tag'] = $tmp_filter['gTag'];unset($tmp_filter['gTag']);
        }

        // if($tmp_filter['is_store'] == 'on' || app::get('b2c')->getConf('gallery.display.stock_goods') != 'true'){
        //     #是否有货
        //     $is_store = $params['is_store'];
        // }

        if(app::get('b2c')->getConf('gallery.display.stock_goods')!='true'){
            $tmp_filter['is_store']='on';
        }


        if($tmp_filter['virtual_cat_id']){
            $tmp_filter = $this->_merge_vcat_filter($tmp_filter['virtual_cat_id'],$tmp_filter);//合并虚拟分类条件
        }

        if($tmp_filter['pTag']){//促销优惠
            $time = time();
            $pTagGoods = app::get('b2c')->model('goods_promotion_ref')->getList('goods_id,apply_platform',array('tag_id'=>$tmp_filter['pTag'],'from_time|sthan'=>$time, 'to_time|bthan'=>$time,'status'=>'true'));
            if($pTagGoods){
                foreach($pTagGoods as $gids){
                    if(strpos($gids['apply_platform'],'2') === false){
                        continue;
                    }
                    $tmp_filter['goods_id'][] = $gids['goods_id'];
                }
            }
            if(empty($tmp_filter['goods_id']) ){
                $tmp_filter['goods_id'] = array(-1);
            }
            unset($tmp_filter['pTag']);
        }

        $filter['filter'] = $tmp_filter;
        $filter['orderby'] = $orderby;
        $filter['showtype'] = $showtype;
        $filter['page'] = $page;
        return $filter;
    }

    /* 根据条件返回搜索到的商品
        * @params array $filter 搜索条件
        * @params int   $page   页码
        * @params string $orderby 排序
        * @return array
        * */
    private function _get_goods($filter,$page=1,$orderby, $page_size=10)
    {
        $goodsModel = app::get('b2c')->model('goods');
        $siteMember = $this->get_current_member();
        if( empty($siteMember['member_id']) ){
            $this->pagedata['login'] = 'nologin';
        }

        $page = $page ? $page : 1;
        //$pageLimit = app::get('b2c')->getConf('gallery.display.listnum');
        $pageLimit = $page_size;
        $this->pagedata['pageLimit'] = $pageLimit;
        $goodsData = $goodsModel->getList('*',$filter,$pageLimit*($page-1),$pageLimit,$orderby,$total=false);
        //self::return_json($page_size);        
        if($goodsData && $total ===false){
            $total = $goodsModel->count($filter);
        }
        $this->pagedata['total'] =  $total;
        $pagetotal= $this->pagedata['total'] ? ceil($this->pagedata['total']/$pageLimit) : 1;
        $max_pagetotal = app::get('b2c')->getConf('gallery.display.pagenum');
        $max_pagetotal = $max_pagetotal ? $max_pagetotal : 100;
        $this->pagedata['pagetotal'] = $pagetotal > $max_pagetotal ? $max_pagetotal : $pagetotal;
        $this->pagedata['page'] = $page;
        //分页
/*        $this->pagedata['pager'] = array(
            'current'=>$page,
            'total'=>$this->pagedata['pagetotal'],
            'link' =>$this->gen_url(array('app'=>'b2c', 'ctl'=>'wap_gallery','act'=>'ajax_get_goods')),
        );*/
        $gfav = explode(',',$_COOKIE['S']['GFAV'][$siteMember['member_id']]);
        foreach($goodsData as $key=>$goods_row){
            if(in_array($goods_row['goods_id'],$gfav)){
                $goodsData[$key]['is_fav'] = 'true';
            }
            //$goodsData[$key]['image_default_id'] = base_storager::image_path($goods_row['image_default_id']);
            $goodsData[$key]['image_default_id'] = $goods_row['image_default_id'];
            if($goods_row['udfimg'] == 'true' && $goods_row['thumbnail_pic']){
                //$goodsData[$key]['image_default_id'] = base_storager::image_path($goods_row['thumbnail_pic']);
                $goodsData[$key]['image_default_id'] = $goods_row['thumbnail_pic'];
            }
            $gids[$key] = $goods_row['goods_id'];
        }

        if($filter['search_keywords'] || $filter['virtual_cat_id']){
            if(kernel::service('server.search_type.b2c_goods') && $searchrule = searchrule_search::instance('b2c_goods') ){
                if($searchrule){
                    $catCount = $searchrule->get_cat($filter);
                }
            }else{
                $sfilter = 'select cat_id,count(cat_id) as count from sdb_b2c_goods WHERE ';
                $sfilter .= $goodsModel->_filter($filter);
                $sfilter .= ' group by cat_id';
                $cats = $goodsModel->db->select($sfilter);
                if($cats){
                    foreach($cats as $cat_row){
                        $catCount[$cat_row['cat_id']] = $cat_row['count'];
                    }
                }
            }
        }
        
        //搜索时的分类
        if(!empty($catCount) && count($catCount) != 1){
            arsort($catCount);
            $this->pagedata['show_cat_id'] = key($catCount);
            $this->pagedata['catArr'] = array_keys($catCount);
            $this->catCount = $catCount;
        }else{
            $this->pagedata['show_cat_id'] = key($catCount);
        }

        //货品
        $goodsData = $this->get_product($gids,$goodsData);

        //促销标签
        /*
        $goodsData = $this->get_goods_promotion($gids,$goodsData);
        */

        //商品标签信息
        /*
        foreach( kernel::servicelist('tags_special.add') as $services ) {
            if ( is_object($services)) {
                if ( method_exists( $services, 'add') ) {
                    $services->add( $gids, $goodsData);
                }
            }
        }*/
        
        //给商品附加预售信息
        /*
        $preparesell_is_actived = app::get('preparesell')->getConf('app_is_actived');
        if($preparesell_is_actived == 'true'){
            $prepare=app::get('preparesell')->model('preparesell_goods');
            if(is_object($prepare))
            {
                foreach ($goodsData as $key => $value) {
                    $prepare_goods = $prepare->getRow('*',array('product_id'=>$value['products']['product_id']));
                    if(!empty($prepare_goods))
                    {
                        $goodsData[$key]['prepare']=$prepare_goods;
                    }
                }
            }
        }*/
        
        if($filter['is_store'] == 'on'){
            $productsModel = app::get('b2c')->model('products');
            foreach($goodsData as $key => $value){
                $products = $productsModel->getlist('product_id,store,freez',array('goods_id'=>$value['goods_id']));
                $is_store = false;
                //foreach($products as $value){
                foreach($products as $item){
                    //if($value['store']>$value['freez']){
                    if($item['store'] > $item['freez']){
                        $is_store = true;
                        break;
                    }
                }
                if(!$is_store){
                    unset($goodsData[$key]);
                }
            }
        }
        
        if(!empty($pagedata)){
            $pagedata=$this->pagedata;
        }
        //这里不需要 gyct
        //$goodsData = $this->get_goods_point($gids,$goodsData);
        return $goodsData;
    }

    /*
    * 获取搜索到的商品的积分信息
    *
    * @params array $gids 搜索到到的商品ID集合
    * @params array $goodsData 搜索到的商品数据
    * @return array
    * */
    private function get_goods_point($gids,$goodsData){
        $pointModel = app::get('b2c')->model('comment_goods_point');
        $goods_point_status = app::get('b2c')->getConf('goods.point.status');
        $this->pagedata['point_status'] = $goods_point_status ? $goods_point_status: 'on';
        if($this->pagedata['point_status'] == 'on'){
            $sdf_point = $pointModel->get_single_point_arr($gids);
            foreach($goodsData as $key=>$row){
                $goodsData[$key]['goods_point'] = $sdf_point[$row['goods_id']];
            }
        }

        return $goodsData;
    }
    /*
    * 获取搜索到的商品的促销信息
    *
    * @params array $gids 搜索到到的商品ID集合
    * @params array $goodsData 搜索到的商品数据
    * @return array
    * */
    private function get_goods_promotion($gids,$goodsData){
        //商品促销
        $time = time();
        $order = kernel::single('b2c_cart_prefilter_promotion_goods')->order();
        $goodsPromotion = app::get('b2c')->model('goods_promotion_ref')->getList('*', array('goods_id'=>$gids, 'from_time|sthan'=>$time, 'to_time|bthan'=>$time,'status'=>'true'),0,-1,$order);
        if($goodsPromotion){
            $black_gid = array();
            foreach($goodsPromotion as $row) {
                if(in_array($row['goods_id'],$black_gid)) continue;
                if(strpos($row['apply_platform'],'2') === false){
                    continue;
                }
                $tags[] = $row['tag_id'];
                $promotionData[$row['goods_id']][] = $row['tag_id'];
                if( $row['stop_rules_processing']=='true' ){
                    $black_gid[] = $row['goods_id'];
                }
            }
        }
        $tagModel = app::get('desktop')->model('tag');
        $sdf_tags = $tagModel->getList('tag_id,tag_name',array('tag_id'=>$tags));
        foreach($sdf_tags  as $tag_row){
            $tagsData[$tag_row['tag_id']] = $tag_row;
        }
        foreach($promotionData as $gid=>$p_row){
            foreach($p_row as $k=>$tag_id){
                $promotion_tags[$gid][$k] = $tagsData[$tag_id];
            }
        }
        foreach($goodsData as $key=>$goods_row){
            $goodsData[$key]['promotion_tags'] = $promotion_tags[$goods_row['goods_id']];
        }
        return $goodsData;
    }

    /*
     * 获取搜索到的商品的默认货品数据，并且格式化货品数据(货品市场价，库存等)
     *
     * @params array $gids 搜索到到的商品ID集合
     * @params array $goodsData 搜索到的商品数据
     * @return array
     * */
    private function get_product($gids,$goodsData){
        $this->pagedata['imageDefault'] = app::get('image')->getConf('image.set');
        $productModel = app::get('b2c')->model('products');
        // $products =  $productModel->getList('*',array('goods_id'=>$gids,'is_default'=>'true','marketable'=>'true'));
        $products =  $productModel->getList('*',array('goods_id'=>$gids,'marketable'=>'true'));
        $temp_product =  array();
        foreach($products as $key=>$row){
            $temp_product[$row['goods_id']][] = $row;
        }
        unset($products);
        foreach($temp_product as $k=>$v){
            $temp = array();
            foreach($v as $goods_id=>$val){
                if($val['is_default'] == 'true'){
                    $temp = $val;
                }
            }
            if( !$temp ){
                $temp = $v[0];
            }
            $products[] = $temp;
        }
        $show_mark_price = app::get('b2c')->getConf('site.show_mark_price');

        #检测货品是否参与special活动
        if($object_price = kernel::service('sepcial_goods_check')){
            $object_price->check_special_goods_list($products);
        }

        $sdf_product = array();
        foreach($products as $key=>$row){
            $sdf_product[$row['goods_id']] = $row;
        }
        foreach ($goodsData as $gk=>$goods_row){
            $product_row = $sdf_product[$goods_row['goods_id']];
            $goodsData[$gk]['products'] = $product_row;
            //市场价
            if($show_mark_price =='true'){
                if($product_row['mktprice'] == '' || $product_row['mktprice'] == null)
                    $goodsData[$gk]['products']['mktprice'] = $productModel->getRealMkt($product_row['price']);
            }

            //库存
            if($goods_row['nostore_sell'] || $product_row['store'] === null){
                $goodsData[$gk]['products']['store'] = 999999;
            }else{
                $store = $product_row['store'] - $product_row['freez'];
                $goodsData[$gk]['products']['store'] = $store > 0 ? $store : 0;
            }
        }
        return $goodsData;
    }




    /*
    * 将列表页中的搜索条件和虚拟分类条件合并
    *
    * @params int $virtual_cat_id 虚拟分类ID
    * @params array $filter  列表页搜索条件
    * */
    private function _merge_vcat_filter($virtual_cat_id,$filter){
        $virCatObj = app::get('b2c')->model('goods_virtual_cat');
        /** 颗粒缓存商品虚拟分类 **/
        if(!cachemgr::get('goods_virtual_cat_'.intval($virtual_cat_id), $vcat)){
            cachemgr::co_start();
            $vcat = $virCatObj->getList('cat_id,cat_path,virtual_cat_id,filter,virtual_cat_name as cat_name',array('virtual_cat_id'=>intval($virtual_cat_id)));
            cachemgr::set('goods_virtual_cat_'.intval($virtual_cat_id), $vcat, cachemgr::co_end());
        }
        $vcat = current( $vcat );
        parse_str($vcat['filter'],$vcatFilters);

        if($filter['cat_id'] && $vcatFilters['cat_id']){
            unset($vcatFilters['cat_id']);
        }
        $filter = array_merge_recursive($filter,$vcatFilters);
        return $filter;
    }
    /*
    *获取商品评论列表
    * */
    public function getCommentList()
    {
        $goodsId = $_GET['goods_id'];
        if(!$goodsId) {
            return self::api_error("商品ID不能为空");
        }
        
        $comment_detial= kernel::single("b2c_goods_description_comments")->show($goodsId,'discuss');
        $commentList = array();
        if (!empty($comment_detial)){
            foreach ($comment_detial['list']['discuss'] as $key => $value) {
                $commentList[$key]['url'] = '';
                $commentList[$key]['name'] = $value['author'];
                $commentList[$key]['time'] = date('Y-m-d h:i',$value['time']);  //评论时间
                $commentList[$key]['content'] = $value['comment'];
                $commentList[$key]['start'] = empty($value['goods_point']) ? 0 :$value['goods_point'];
                $commentList[$key]['children'][]['contnet'] = $value['items'][0]['comment'];//商家回复
            }
        }

        $api_data = array(
            'msg' => '',
            'code' => '0',
            'commentList'=> $commentList,
        );
        self::return_json($api_data);
    }

    /**
     * 商品详情
     */

    public function goodsDetail()
    {
        $goods_id = floatval($_GET['id']);
        if( ! $goods_id ) {
            return self::api_error("商品ID不能为空");
        }
        
        $member = $this->member_info;

        $mdl_goods = app::get('b2c')->model('goods');
        $aGoods = $mdl_goods->dump($goods_id,'*','default');
        $aGoods['preview'] =  base_storager::image_path($aGoods['image_default_id']);
        
        $productModel = app::get('b2c')->model('products');
        $productList = $productModel->getList('*',array('goods_id'=>$goods_id));
        if(empty($productList)) {
            return self::api_error("商品不存在");
        }
        
        $productId = $productList[0]['product_id'];
        
        //基本信息
        $siteMember = $this->get_current_member();
        //$aGoodsList = $mdl_goods->getList('*', array('goods_id' => $goods_id));
        $productBasic = $this->_get_product_basic($productId,$aGoods,$siteMember);
        //商品详情
        $goodsDetail = $this->_get_goods_detail($goods_id);
        
        //self::return_json($productBasic);exit;

        //商品轮播图
        $mdl_img   = app::get('image')->model('image');
        $photoList = array();
        foreach ($productBasic['images'] as $val){            
            
            //判断是否存在缩略图
            /*
            if(base_storager::image_path($val['image_id'],'s') == base_storager::image_path($val['image_id'],'l')){
                $mdl_img->rebuild($val['image_id'],array('L','M','S'));
            }*/
            
            $photoList[] = array(
                "goodsId"=> $productBasic['goods_id'],
                "id"=>$val['attach_id'],
                "photo"=>base_storager::image_path($val['image_id'],'l'),
                "thumPhoto"=>base_storager::image_path($val['image_id'],'l'),
                //"image_s"=>base_storager::image_path($val['image_id'],'s'),
                //"image_m"=>base_storager::image_path($val['image_id'],'m'),
                //"image_l"=>base_storager::image_path($val['image_id'],'l'),
                //"image_id"=>$val['image_id'],
                //"thumPhoto"=> $val['image_id']
            );
        }
        
        //特殊商品过滤掉第一张图
        $this->_unset_first_image($productBasic['goods_bn'], $photoList);
        
        $goodsSkuNameList = array();

        $goodsSkuList = array();
        $goods_stockNum = 0;
        $goodsSkuValIds = array();
        $first_sku = array();
        foreach ($productList as $value){       
            $specInfos = explode('、',$value['spec_info']);
            $specTemp = array();
            foreach ($specInfos as $val){
                $spec = explode('：',$val);
                array_push($specTemp,$spec[0]);
            }
            
            //扣除冻结库存 
            $stockNum = $value['store'];
            if($value['freez']) $stockNum -= $value['freez'];
            if($stockNum < 0) $stockNum = 0;
            
            $goodsSkuList[] = array(
                "goodsCode"=> $value['bn'],
                "goodsId"=> $value['goods_id'],
                "id"=> $value['product_id'],
                "price"=> $this->_formatPrice($value['price']),
                "saleCount"=> 0,
                "skuNameIds"=> json_encode(array_values($value['spec_desc']['spec_private_value_id'])),
                "skuNames"=> json_encode($specTemp),
                "skuValIds"=> json_encode(array_values($value['spec_desc']['spec_value_id'])),
                "skuVals"=> json_encode(array_values($value['spec_desc']['spec_value'])),
                "stockNum"=> $stockNum,
                "stockNumWarn"=> 0
            );
            
            if($value['is_default'] == 'true'){
                $defaultSkuStore = $stockNum;
                $goodsSkuValIds = array_values($value['spec_desc']['spec_value_id']); 
                $first_sku = array_values($value['spec_desc']['spec_value']);
            }

            $goods_stockNum += $stockNum;
        }
        
        //todo 这里好像没用。因为DB里没有数据
        $attrList = array();
        /*
        if($aGoods['brand']['brand_id']){
            $brands = app::get('b2c')->model('brand')->getList('brand_id,brand_name',array('brand_id'=>$aGoods['brand']['brand_id'],'disabled'=>'false'));
            $attrList[] = array(
                'attrName' => '品牌',
                'attrNameId' => $aGoods['brand']['brand_id'],
                'attrVal' => $brands[0]['brand_name'],
                'goodsId' => $goods_id,
                'id' => '22141',
            );
        }*/
        
        if($aGoods['bn']){
            $attrList[] = array(
                'attrName' => '货号',
                'attrNameId' => '',
                'attrVal' => $aGoods['bn'],
                'goodsId' => $goods_id,
                'id' => '22142',
            );
        }
        
        foreach ($productBasic['props'] as $v){
            $attrList[] = array(
                'attrName' => $v['prop'],
                'attrNameId' => '',
                'attrVal' => $v['name'],
                'goodsId' => $goods_id,
                'id' => '22142',
            );
        }
        
        /*
        if(!empty($productBasic['props'])){
            foreach ($productBasic['props'] as $value){
                $attrList[] = array(
                    'attrName' => '属性',
                    'attrNameId' => '',
                    'attrVal' => $value['name'],
                    'goodsId' => $value['value'],
                    'id' => '',
                );
            }
        }*/
        
        //解析sku属性
        foreach($aGoods['spec'] as $k=>$v){ 
            $skuValList = array();
            foreach($v['option'] as $kk=>$vv){
                
                if( ! $skuValList) {
                    //$goodsSkuValIds[] = $vv['spec_value_id']; 
                    //$first_sku[] = $vv['spec_value'];
                }
                
                $current = false;
                if(in_array($vv['spec_value'], $first_sku)){
                    $current = true;
                }
                
                $skuValList[] = array(
                    "current"=> $current,
                    "skuVal"=> $vv['spec_value'],
                    "skuImage"=> base_storager::image_path($vv['spec_image']),
                    "skuNameId"=> $k,
                    "skuValId"=> $vv['spec_value_id']
                );
            }   
            
            $goodsSkuNameList[] = array(
                "skuNameId"=> $v['spec_id'],
                "skuName"=> $v['spec_name'],
                "skuValList"=> $skuValList,
            );
        }

        //==================================
        //elrond : 前端要求这个数据使用数组而不是$id=>$val的对象
        foreach($goodsSkuNameList as $k => $skuName)
        {
            $goodsSkuNameList[$k]['skuValList'] = array_values($goodsSkuNameList[$k]['skuValList']);
        }
        //==================================
        
        
        //过滤没用的html代码
        if($goodsDetail){
            $filter_html = '/<img(.+?)src="https:\/\/assets\.alicdn\.com(.+?)>/';        
            $goodsDetail = preg_replace($filter_html,'',$goodsDetail);
            
            $filter_html = '/<p(.+?)>/';        
            $goodsDetail = preg_replace($filter_html,'<p>',$goodsDetail);
        }
        
        //价格说明图片
        $goodsDetail .= '<img src="'.kernel::base_url(1).'/wxapp/images/about_price.gif" />';

        $api_data = array(
            'msg' => '',
            'code' => '0',
            'validDate' => $aGoods['status'] == 'true'? '1' : '0',
            'data' => array(
                'attrList' => $attrList,
                'brandName' => '',
                'businessId' => '',
                'businessName' => '',//这里应该是商家名称
                'code' => $productBasic['goods_bn'],
                'detailInfo' => (string)$goodsDetail,
                'evaluateCount' => '0',
                'freeShipNum' => '99999999',
                'freight' => '0',
                'goodsSkuId' => $aGoods['bn'],
                'goodsSkuList' => $goodsSkuList,
                'goodsSkuNameList' => $goodsSkuNameList,
                'goodsSkuValIds' => array_values($goodsSkuValIds),
                'goodsSkuVals' => $first_sku,
                'id' => $aGoods['goods_id'],
                'logo' => $aGoods['preview'], //商品图片
                'marketPrice' => $this->_formatPrice($aGoods['mktprice']),
                'minBuyNum' => '3',
                'name' => $aGoods['name'],
                'photoList' => $photoList,
                'price' => $this->_formatPrice($productBasic['price']),
                'saleCount' => $aGoods['buy_count'],
                'shareAmount' => '5',
                'shareTimes' => '3',
                'shareTips' => '废弃：此商品分享3个好友',
                'sourceFlag' => '1',
                'startTime' => '2017-10-05 15:11:01',
                'status' => '1',
                'stockNum' => $goods_stockNum,
                'thumLogo' => $aGoods['image_default_id'],
                'validEndTime' => '2099-10-20 23:55:50',
                'wholeNum' => '3',
                'wholePrice' => '63',
                'promotion' => $productBasic['promotion'],
                'spec' => $productBasic['spec'],
                'defaultSkuStore' => $defaultSkuStore,
                'isFavorite' => $this->_is_favorite($goods_id, $member['member_id']),
            ),
        );
        self::return_json($api_data);
    }
    
    private function _is_favorite($goods_id, $member_id=0)
    {
        if( ! $member_id){
            return 0;
        }
        
        $obj_member = app::get('b2c')->model('member_goods');
        $aData = $obj_member->get_member_goods($member_id, $goods_id);
        return count($aData) ? 1 : 0;   
    }

    private function get_current_member(){
        return self::user_auth();
    }

    //货品基本数据
    function _get_product_basic($productId, $aGoods, $siteMember)
    {
        $goodsObject = kernel::single('b2c_goods_object');
        $productBasic= array();
        $productBasic['goods_id'] = $aGoods['goods_id'];
        $productBasic['product_id'] = $aGoods['product']['product_id'];
        $productBasic['product_bn'] = $aGoods['product']['bn'];
        $productBasic['price'] = $aGoods['price'];
        $productBasic['intro'] = $aGoods['intro'];
        $productBasic['unit'] = $aGoods['unit'];
        $productBasic['title'] = $aGoods['name'];//主标题
        $productBasic['brief'] = $aGoods['brief'];//副标题
        $productBasic['product_marketable'] = $aGoods['product']['marketable'];//是否上架
        $productBasic['goods_marketable'] = $aGoods['marketable'];//是否上架
        $productBasic['nostore_sell'] = $aGoods['nostore_sell'];//是否开启无库存销售

        $goodsBasic = $goodsObject->get_goods_basic($aGoods['goods_id'], $aGoods);
        if($goodsBasic['type']['setting']['use_params']){
            $productBasic['params'] = $this->_get_goods_params($aGoods['params']);
        }
        $productBasic['goods_bn'] = $goodsBasic['bn'];//商品编号
        $productBasic['type_name'] = $goodsBasic['type']['name'];//商品类型名称
        $productBasic['cat_name'] = $goodsBasic['category']['cat_name'];//商品分类名称
        $productBasic['brand']['brand_name'] = $goodsBasic['brand']['brand_name'];//商品品牌名称
        $this->brand_name = $goodsBasic['brand']['brand_name'];//seo 品牌名称
        $productBasic['brand']['brand_id'] = $goodsBasic['brand']['brand_id'];//商品品牌ID

        //促销
        if(empty($siteMember['member_lv'])){
            $siteMember['member_lv'] = '1';
        }
        $productPromotion= $this->_get_goods_promotion($aGoods['goods_id'],$aGoods,$siteMember['member_lv']);
        $productBasic['promotion'] = $productPromotion;//商品促销
        
        //获取预售信息
        $prepare=kernel::service('prepare_prepare');

        if($prepare){
            $pre=$prepare->getSpecialProduct($productId);
            if(!empty($pre)){
                $pre['nowtime']=time();
                $productBasic['prepare'] = $pre;
                $productBasic['promotion_type'] = $pre['promotion_type'];
            }
        }

        //扩展属性
        $goodsProps = $this->_get_goods_props($aGoods['type']['props'], $aGoods['props']);
        
        //self::return_json($goodsBasic);exit;
        
        $productBasic['props'] = $goodsProps;//商品类型中扩展属性
        //规格
        $goodsSpec = $this->_get_goods_spec($aGoods);
        $productBasic['spec'] = $goodsSpec;//商品规格

        #货品价格 货品库存 ajax调用

        #//货品类型的自定义tab
        $goodsTypeTab = $this->_get_goods_type_tab($goodsBasic['type']);
        $productBasic['type_tab'] = $goodsTypeTab;

        //没有默认货品图片则显示商品所有图片，否则显示关联货品图片
        $default_spec_image = app::get('b2c')->getConf('spec.default.pic');
        foreach($goodsSpec['product'] as $k=>$row){
            $spec_goods_images = $goodsSpec['goods'][$k][$row]['spec_goods_images'];
            if(!empty($spec_goods_images) && $spec_goods_images != $default_spec_image){
                $imagesArr = explode(',',$spec_goods_images);
                foreach( (array)$imagesArr as $image_id ){
                    $productBasic['images'][]['image_id'] = $image_id;
                }
            }
        }
        
        if(empty($productBasic['images'])){
            $goodsImages = $this->_get_goods_image($aGoods);
            $productBasic['images'] = $goodsImages;//商品图片
            $productBasic['image_default_id'] = base_storager::image_path($aGoods['image_default_id']);//商品图片
        }else{
            $productBasic['image_default_id'] = base_storager::image_path($productBasic['images'][0]['image_id']);//商品图片
        }

        //货品价格
        $productPrice = $this->_get_product_price($productId,$aGoods,$siteMember['member_lv']);
        $this->pagedata['product_price'] = $productPrice;
        //货品库存
        // $this->ajax_product_store($productId,$aGoods['store_prompt']);
        $this->_get_product_store($productId);
        $gfav = explode(',',$_COOKIE['S']['GFAV'][$siteMember['member_id']]);
        if(in_array($aGoods['goods_id'], $gfav)){
            $productBasic['is_fav'] = true;
        }
        return $productBasic;
    }

    //价格数据处理
    function _get_product_price($productId,$aGoods,$member_lv=null){
        $goodsPrice = array();
        $objCurrency = app::get('ectools')->model('currency');
        $money_format = json_decode($this->pagedata['money_format'],true);
        $productMemberPrice['price'] = $objCurrency->changer_odr($aGoods['product']['price'], $_COOKIE['S']['CUR'], true, false, $money_format['decimals'], $money_format['fonttend_decimal_type']);
        $productsModel = app::get('b2c')->model("products");
        //市场价
        $setting_mktprice = app::get('b2c')->getConf('site.show_mark_price');//前台是否显示市场价
        if($setting_mktprice  == 'true'){
            if( $aGoods['product']['mktprice'] == '' || $aGoods['product']['mktprice'] == null ){
                $mktprice = $aGoods['mktprice'];
            }else{
                $mktprice = $aGoods['product']['mktprice'];
            }
            if( $mktprice == '' || $mktprice == null ){
                $productMemberPrice['mktprice'] = $productsModel->getRealMkt($aGoods['price']);
            }else{
                $productMemberPrice['mktprice'] = $mktprice;
            }
            $productMemberPrice['mktprice'] = $objCurrency->changer_odr($productMemberPrice['mktprice'], $_COOKIE['S']['CUR'], true, false, $money_format['decimals'], $money_format['fonttend_decimal_type']);
        }


        $setting_member_price = app::get('b2c')->getConf('site.member_price_display');//前台是否显示会员价
        $show_member_price=array(1,3,4);
        $userObject = kernel::single('b2c_user_object');
        $siteMember = $userObject->get_current_member();
        $member_lv_id=$siteMember['member_lv'];
        if(in_array($setting_member_price,$show_member_price)){
            //会员价
            $memberLv = app::get('b2c')->model('member_lv')->getList('member_lv_id,name,dis_count');
            $customMemberPrice = app::get('b2c')->model('goods_lv_price')->getList('*',array('product_id'=>$productId));
            if(!empty($customMemberPrice) ){
                foreach($customMemberPrice as $value){
                    $tempCustom[$value['level_id']] = $value;
                }
            }
            $minPrice = null;
            $i = 0;
            foreach($memberLv as $memberValue){
                if( !empty($tempCustom[$memberValue['member_lv_id']]) ){
                    $productMemberPrice['mlv_price'][$i]['name'] = $memberValue['name'];
                    $productMemberPrice['mlv_price'][$i]['price'] = $tempCustom[$memberValue['member_lv_id']]['price'];
                    $productMemberPrice['mlv_price'][$i]['price'] = $objCurrency->changer_odr($productMemberPrice['mlv_price'][$i]['price'], $_COOKIE['S']['CUR'], true, false, $money_format['decimals'], $money_format['fonttend_decimal_type']);
                    if($memberValue['member_lv_id'] == $member_lv_id){
                        $productMemberPrice['the_mlv_price'] = $productMemberPrice['mlv_price'][$i]['price'];
                    }
                }else{
                    $productMemberPrice['mlv_price'][$i]['name'] = $memberValue['name'];
                    $productMemberPrice['mlv_price'][$i]['price'] = $aGoods['product']['price'] * $memberValue['dis_count'];
                    $productMemberPrice['mlv_price'][$i]['price'] = $objCurrency->changer_odr($productMemberPrice['mlv_price'][$i]['price'], $_COOKIE['S']['CUR'], true, false, $money_format['decimals'], $money_format['fonttend_decimal_type']);
                    if($memberValue['member_lv_id'] == $member_lv_id){
                        $productMemberPrice['the_mlv_price'] = $productMemberPrice['mlv_price'][$i]['price'];
                    }
                }
                if($minPrice === null ){
                    $minPrice = $productMemberPrice['mlv_price'][$i]['price'];
                }else{
                    if($minPrice >= $productMemberPrice['mlv_price'][$i]['price']){
                        $minPrice = $productMemberPrice['mlv_price'][$i]['price'];
                    }
                }
                $i++;
            }
        }//end
        $productMemberPrice['minprice'] = $minPrice;
        return $productMemberPrice;
    }

    /*商品详情页库存显示*/
    function _get_product_store($product_id){
        $product = app::get('b2c')->model('products')->getList('goods_id,store,freez',array('product_id'=>$product_id));
        if($product){
            $goodsdata = app::get('b2c')->model('goods')->getList('goods_id,nostore_sell,store,store_prompt',array('goods_id'=>$product[0]['goods_id']));
            if($goodsdata && ($goodsdata[0]['nostore_sell'] || $goodsdata[0]['store'] === null)){
                $store['store'] = 999999;//暂时表示库存无限大
            }else{
                $goodsStore = $product[0]['store'] - $product[0]['freez'];
                $store['store'] = ($goodsStore >= 0)? $goodsStore : 0 ;
            }
            $show_storage = app::get('b2c')->getConf('site.show_storage');
            switch($show_storage){
                case '1';//不显示库存提示
                    $store['title'] = null;
                    break;
                case '2';//显示库存数量提示
                    $store['title'] =  $store['store'];
                    break;
                case '3';//启用库存优化方案
                    if($goodsdata[0]['store_prompt']){
                        $store_prompt = app::get('b2c')->model('goods_store_prompt')->getList('`values`',array('prompt_id'=>$goodsdata[0]['store_prompt']));
                    }
                    if($store_prompt){
                        $values = unserialize($store_prompt[0]['values']);
                        foreach($values as $params){
                            if($store['store'] >= $params['min'] && $store['store'] < $params['max']){
                                $store['title'] = $params['title']; break;
                            }
                        }
                    }
                    break;
            }
            $this->pagedata['product_store'] = $store;
            return $store;
        }
    }

    function _get_goods_props($arrProps, $aGoods)
    {
        //self::return_json($arrProps);exit;
        
        if( empty($arrProps) ){
            return null;
        }
        $goodsProps = array();

        for ($i=1;$i<=50;$i++){
            //1-20 select 21-50 input
            if ($aGoods['p_'.$i] ){
                $propsValueId = $aGoods['p_'.$i];
                $k = $arrProps[$i]['ordernum'].'_'.$i;
                if( $i <= 20){
                    $goodsProps[$k]['name'] = $arrProps[$i]['options'][$aGoods['p_'.$i]['value']];
                    $goodsProps[$k]['value'] = $aGoods['p_'.$i]['value'];
                }else{
                    //$goodsProps[$k]['name'] = $arrProps[$i]['name'];
                    $goodsProps[$k]['name'] = $propsValueId['value'];
                    $goodsProps[$k]['value'] = $propsValueId['value'];
                }
                
                $goodsProps[$k]['prop'] = $arrProps[$i]['name'];

                //如果商品类型扩展属性改变，则商品中的设置需要重现设置，原先设置无效
                if(empty($goodsProps[$k]['name']) || empty($goodsProps[$k]['value']) ){
                    unset($goodsProps[$k]);
                    continue;
                }
            }
        }
        return $goodsProps;
    }

    //获取货品规格数据
    function _get_goods_spec($aGoods){
        $goodsSpec = array();
        $products = app::get('b2c')->model('products')->getList('product_id,spec_desc,store,freez,marketable',array('goods_id'=>$aGoods['goods_id']));
        if($aGoods['spec_desc']){
            $goodsSpec['goods'] = $aGoods['spec_desc'];
            $goodsSpec['product'] = $aGoods['product']['spec_desc']['spec_private_value_id'];
            foreach($products as $row){
                $products_spec = $row['spec_desc']['spec_private_value_id'];
                $diff_class = array_diff_assoc($products_spec,$goodsSpec['product']);//求出当前货品和其他货品规格的差集
                if(count($diff_class) >= 1){
                    $goodsSpec['goods'][key($diff_class)][current($diff_class)]['product_id'] = $row['product_id'];
                    $goodsSpec['goods'][key($diff_class)][current($diff_class)]['marketable'] = $row['marketable'];
                    if($row['store'] === '' || $row['store'] === null){
                        $product_store = '999999';
                    }else{
                        $product_store = $row['store']-$row['freez'];
                    }
                    $goodsSpec['goods'][key($diff_class)][current($diff_class)]['store'] = $product_store;
                }
            }

            foreach($aGoods['spec_desc'] as $specId=>$specValue){
                $arrSpecId['spec_id'][] = $specId;
            }

            $arrSpecName = app::get('b2c')->model('specification')->getList('spec_name,spec_id,spec_type',$arrSpecId);
            foreach($arrSpecName as $specItem){
                $goodsSpec['specification']['spec_name'][$specItem['spec_id']] = $specItem['spec_name'];
                $goodsSpec['specification']['spec_type'][$specItem['spec_id']] = $specItem['spec_type'];

            }
        }
        return $goodsSpec;
    }
    function _get_goods_type_tab($type){
        if($type['setting']['use_tab']){
            return $type['tab'];
        }else{
            return array();
        }
    }


    /*
     *获取商品促销数据
     * */
    function _get_goods_promotion($goodsId,$aGoods,$member_lv_id){
        $goodsPromotion = kernel::single('b2c_goods_object')->get_goods_promotion($goodsId,'2');
        $productPromotion = array();
        $giftId = array();
        //商品促销
        foreach($goodsPromotion['goods'] as $row){
            if(strpos($row['apply_platform'],'2') === false){
                continue;
            }
            $temp = is_array($row['action_solution']) ? $row['action_solution'] : @unserialize($row['action_solution']);
            if(key($temp) == 'gift_promotion_solutions_gift'){
                if(strpos($row['member_lv_ids'],$member_lv_id) === false){
                    continue;
                }
                $giftId = array_merge($giftId,$temp['gift_promotion_solutions_gift']['gain_gift']);
                continue;
            }

            if(isset($same_rule[key($temp)]) && $same_rule[key($temp)]){
                continue;
            }else{
                $same_rule[key($temp)] = true;
            }

            $ruleData = app::get('b2c')->model('sales_rule_goods')->getList('name',array('rule_id'=>$row['rule_id']));
            $productPromotion['goods'][$row['rule_id']]['name'] = $ruleData[0]['name'];
            $productTag = kernel::single(key($temp))->get_desc_tag();
            $productPromotion['goods'][$row['rule_id']]['tag'] = $productTag['name'];
            if(strpos($row['member_lv_ids'],$member_lv_id) === false){
                $productPromotion['goods'][$row['rule_id']]['use'] = 'false';
            }else{
                $productPromotion['goods'][$row['rule_id']]['use'] = 'true';
            }
        }

        //订单促销
        $giftCartObject = kernel::single('gift_cart_object_goods');
        foreach($goodsPromotion['order'] as $row){
            if(strpos($row['apply_platform'],'2') === false){
                continue;
            }
            if(strpos($row['member_lv_ids'],$member_lv_id) === false){
                continue;
            }
            $temp = is_array($row['action_solution']) ? $row['action_solution'] : @unserialize($row['action_solution']);
            if(key($temp) == 'gift_promotion_solutions_gift'){
                $gain_gift = $temp['gift_promotion_solutions_gift']['gain_gift'];
                $giftId = array_merge($giftId,$gain_gift);
                if(!$giftCartObject->check_gift($giftId)){
                    continue;
                }
            }
            $productTag = kernel::single(key($row['action_solution']))->get_desc_tag();
            $productPromotion['order'][$row['rule_id']]['name'] = $row['name'];
            $productPromotion['order'][$row['rule_id']]['tag'] = $productTag['name'];
        }
        //赠品
        if($giftId){
            $giftRef = app::get('gift')->model('ref')->getList('*',array('product_id'=>$giftId,'marketable'=>'true'));
            if($giftRef){
                foreach($giftRef as $key=>$row){
                    if($row['marketable'] == 'false') continue;
                    if($row['cat_id']){
                        $giftCat = app::get('gift')->model('cat')->getList('*',array('cat_id'=>$row['cat_id']));
                        if($giftCat[0]['ifpub'] == 'false') continue;
                    }
                    $newGiftId[] = $row['product_id'];
                }
            }

            $aGift = app::get('b2c')->model('products')->getList('goods_id,product_id,name,store,freez',array('product_id'=>$newGiftId,'marketable='=>'true') );
            foreach($aGift as $key=>$row){
                $arrGoodsId[$key] = $row['goods_id'];
                if(is_null($row['store'])){
                    $aGift[$key]['store'] = 999999;
                }
            }
            $image = app::get('b2c')->model('goods')->getList('image_default_id,goods_id,nostore_sell,marketable',array('goods_id'=>$arrGoodsId) );
            sort($image);
            foreach($aGift as $key=>$row){
                if($image[$key]['marketable'] == 'false'){
                    unset($aGift[$key]);continue;
                }
                $aGift[$key]['image_default_id'] = $image[$key]['image_default_id'];
                if($row['nostore_sell']){
                    $aGift[$key]['store'] = 999999;
                }
            }
            $productPromotion['gift'] = $aGift;
        }
        return $productPromotion;
    }
    
    /*
    *获取商品图片数据
    * */
    function _get_goods_image($aGoods)
    {
        $image = app::get("image")->model("image_attach");
        $image_data = $image->getList("attach_id,image_id",array("target_id"=>intval($aGoods['goods_id']),'target_type'=>'goods'));
        foreach($image_data as $img_k=>$img_v){
            $goodsImages[$img_v['attach_id']] = $img_v;
            //$goodsImages[$img_v['attach_id']]['image_id'] = base_storager::image_path($img_v['image_id']);
            $goodsImages[$img_v['attach_id']]['image_id'] = $img_v['image_id'];
        }
        return $goodsImages;
    }

    //商品详情
    function _get_goods_detail($goodsId){
        $objGoods = app::get('b2c')->model('goods');
        $aGoods_list = $objGoods->getList("intro,wapintro",array('goods_id'=>$goodsId));
        $goodsDetail = ($aGoods_list[0]['wapintro'] && $aGoods_list[0]['wapintro'] !='&nbsp;') ? $aGoods_list[0]['wapintro'] : $aGoods_list[0]['intro'];
        return $goodsDetail;
    }

    private function _formatPrice($price)
    {
        return sprintf("%.2f",$price);
    }

    /**
     * @name   小数位截取格式化金额  例如 100000.00 -> 100,000.00
     * @param  float    $num  [格式化前的金额]
     * @param  integer  $dist [保留的小数位数]
     * @param  BOOL     $zeroComplete [小数位不够dist时，是否用0补齐]
     * @return [type]        [description]
     */
    function numberFormat($num = 0, $dist =0, $zeroComplete = TRUE) {
        if (!preg_match('/^(-?\d+)(\.\d+)?$/', $num)) {
            return $num;
        }

        if ($dist > 4) {
            $dist = 4;
        }else if ($dist <= 0) {
            $dist = 0;
        }
        if (!is_bool($zeroComplete)) {
            $zeroComplete = TRUE;
        }
        $newNum = floor($num * pow(10, $dist)) / pow(10, $dist);
        return $newNum;
    }


    /**
     * 根据分类ID提供筛选条件，并且返回已选择的条件数据
     * @params int $cat_id 分类ID
     * @params array $filter 已选择的条件
     */
    private function screen($cat_id,$filter){
        if ( empty($cat_id) ) {
            $screen = array();
        }
        $screen['cat_id'] = $cat_id;
        $cat_id = $cat_id ?  $cat_id : $this->pagedata['show_cat_id'];
        //搜索时的分类
        if(!$screen['cat_id'] && count($this->pagedata['catArr']) > 1){
            $searchCat = app::get('b2c')->model('goods_cat')->getList('cat_id,cat_name',array('cat_id'=>$this->pagedata['catArr']));
            $i=0;
            foreach($this->catCount as $catid=>$num){
                $sort[$catid] = $i;
                if($i == 9) break;
                $i++;
            }
            foreach($searchCat as $row){
                $screen['search_cat'][$sort[$row['cat_id']]] = $row;
            }
            ksort($screen['search_cat']);
        }

        //商品子分类
        $show_cat = app::get('b2c')->getConf('site.cat.select');
        if($show_cat == 'true'){
            $sCatData = app::get('b2c')->model('goods_cat')->getList('cat_id,cat_name',array('parent_id'=>$cat_id));
            $screen['cat'] = $sCatData;
        }

        cachemgr::co_start();
        if(!cachemgr::get("goodsObjectCat".$cat_id, $catInfo)){
            $goodsInfoCat = app::get("b2c")->model("goods_cat")->getList('*',array('cat_id'=>$cat_id) );
            $catInfo = $goodsInfoCat[0];
            cachemgr::set("goodsObjectCat".$cat_id, $catInfo, cachemgr::co_end());
        }
        $this->goods_cat = $catInfo['cat_name'];//seo

        cachemgr::co_start();
        if(!cachemgr::get("goodsObjectType".$catInfo['type_id'], $typeInfo)){
            $typeInfo = app::get("b2c")->model("goods_type")->dump(array('type_id'=>$catInfo['type_id']) );
            cachemgr::set("goodsObjectType".$catInfo['type_id'], $typeInfo, cachemgr::co_end());
        }
        $this->goods_type = $typeInfo['name'];//seo

        if($typeInfo['price'] && $filter['price'][0]){
            $active_filter['price']['title'] = $this->app->_('价格');
            $active_filter['price']['label'] = 'price';
            $active_filter['price']['options'][0]['data'] =  $filter['price'][0];
            foreach($typeInfo['price'] as $key=>$price){
                $price_filter = implode('~',$price);
                if($filter['price'][0] == $price_filter){
                    $typeInfo['price'][$key]['active'] = 'active';
                    $active_arr['price'] = 'active';
                }
                $active_filter['price']['options'][0]['name'] = $filter['price'][0];
            }
        }
        $screen['price'] = $typeInfo['price'];

        if ( $typeInfo['setting']['use_brand'] ){
            $type_brand = app::get('b2c')->model('type_brand')->getList('brand_id',array('type_id'=>$catInfo['type_id']));
            if ( $type_brand ) {
                foreach ( $type_brand as $brand_k=>$brand_row ) {
                    if( isset($filter['brand_id']) && ($brand_row['brand_id'] != $filter['brand_id']) ){
                        continue;
                    }
                    $brand_ids[$brand_k] = $brand_row['brand_id'];
                }
            }
            $brands = app::get('b2c')->model('brand')->getList('brand_id,brand_name',array('brand_id'=>$brand_ids,'disabled'=>'false'));
            //是否已选择
            foreach($brands as $b_k=>$row){
                if(in_array($row['brand_id'],$filter['brand_id'])){
                    $brands[$b_k]['active'] = 'active';
                    $active_arr['brand'] = 'active';
                    $active_filter['brand']['title'] = $this->app->_('品牌');;
                    $active_filter['brand']['label'] = 'brand_id';
                    $active_filter['brand']['options'][$row['brand_id']]['data'] =  $row['brand_id'];
                    $active_filter['brand']['options'][$row['brand_id']]['name'] = $row['brand_name'];
                }
            }
            $screen['brand'] = $brands;
        }

        //扩展属性
        if ( $typeInfo['setting']['use_props'] && $typeInfo['props'] ){
            foreach ( $typeInfo['props'] as $p_k => $p_v){
                if ( $p_v['search'] != 'disabled' ) {
                    $props[$p_k]['name'] = $p_v['name'];
                    $props[$p_k]['goods_p'] = $p_v['goods_p'];
                    $props[$p_k]['type'] = $p_v['type'];
                    $props[$p_k]['search'] = $p_v['search'];
                    $props[$p_k]['show'] = $p_v['show'];
                    $propsActive = array();
                    if($p_v['options']){
                        foreach($p_v['options'] as $propItemKey=>$propItemValue){
                            $activeKey = 'p_'.$p_v['goods_p'];
                            if($filter[$activeKey] && in_array($propItemKey,$filter[$activeKey])){
                                $active_filter[$activeKey]['title'] = $p_v['name'];
                                $active_filter[$activeKey]['label'] = $activeKey;
                                $active_filter[$activeKey]['options'][$propItemKey]['data'] =  $propItemKey;
                                $active_filter[$activeKey]['options'][$propItemKey]['name'] = $propItemValue;
                                $propsActive[$propItemKey] = 'active';
                            }
                        }
                    }
                    $props[$p_k]['options'] = $p_v['options'];
                    $props[$p_k]['active'] = $propsActive;
                }
            }

            $screen['props'] = $props;
        }

        //规格
        $gType = app::get("b2c")->model('goods_type');
        $SpecList = $gType->getSpec($catInfo['type_id'],1);//获取关联的规格
        if($SpecList){
            foreach($SpecList as $speck=>$spec_value){
                if($spec_value['spec_value']){
                    foreach($spec_value['spec_value'] as $specKey=>$SpecValue){
                        $activeKey = 's_'.$speck;
                        if($filter[$activeKey] && in_array($specKey,$filter[$activeKey])){
                            $active_filter[$activeKey]['title'] = $spec_value['name'];
                            $active_filter[$activeKey]['label'] = $activeKey;
                            $active_filter[$activeKey]['options'][$specKey]['data'] =  $specKey;
                            $active_filter[$activeKey]['options'][$specKey]['name'] = $SpecValue['spec_value'];
                            $specActive[$specKey] = 'active';
                        }
                    }
                }
                $SpecList[$speck]['active'] = $specActive;
            }
        }
        $screen['spec'] = $SpecList;

        //排序
        $orderBy = app::get("b2c")->model('goods')->orderBy();
        $screen['orderBy'] = $orderBy;

        //标签
        $tagFilter['app_id'][] = 'b2c';
        $giftAppActive = app::get('gift')->is_actived();
        if($giftAppActive){
            $tagFilter['app_id'][] = 'gift';
        }
        $progetcouponAppActive = app::get('progetcoupon')->is_actived();
        if($progetcouponAppActive){
            $progetcouponAppActive['app_id'][] = 'progetcoupon';
        }
        $tags = app::get('desktop')->model('tag')->getList('*',$tagFilter);
        if($filter['pTag']){
            $active_arr['pTags'] = 'active';
        }
        foreach($tags as $tag_key=>$tag_row){
            if($tag_row['tag_type'] == 'goods'){//商品标签
                if(in_array($tag_row['tag_id'],$filter['gTag'])){
                    $screen['tags']['goods'][$tag_key]['active'] = 'checked';
                }
                $screen['tags']['goods'][$tag_key]['tag_id'] = $tag_row['tag_id'];
                $screen['tags']['goods'][$tag_key]['tag_name'] = $tag_row['tag_name'];
            }elseif($tag_row['tag_type'] == 'promotion'){//促销标签
                if(in_array($tag_row['tag_id'],$filter['pTag'])){
                    $screen['tags']['promotion'][$tag_key]['active'] = 'active';
                    $active_filter['pTag']['title'] = $this->app->_('促销商品');;
                    $active_filter['pTag']['label'] = 'pTag';
                    $active_filter['pTag']['options'][$tag_row['tag_id']]['data'] =  $tag_row['tag_id'];
                    $active_filter['pTag']['options'][$tag_row['tag_id']]['name'] = $tag_row['tag_name'];
                }
                $screen['tags']['promotion'][$tag_key]['tag_id'] = $tag_row['tag_id'];
                $screen['tags']['promotion'][$tag_key]['tag_name'] = $tag_row['tag_name'];
            }
        }
        $this->pagedata['active_arr'] = $active_arr;
        $return['screen'] = $screen;
        $return['active_filter'] = $active_filter;
        $return['seo_info'] = $catInfo['seo_info'];
        return $return;
    }

    public function _unset_first_image($bn, &$images)
    {
        //天猫导入的只有5张图
        if(count($images) != 5){
            return;
        }
        
        $filter_goods_bn_arr = array('7379041494','7379011534','7379036123','7379040123','7379028834','7379029833','7379030833','7379037123','7379039826','7379038826','7379024340','7379071918','7379072147','7379063123','7379055340','7379064201','7379044494','7379056123','7379057340','7379061340','7316030143','7316016834','7316015834','7316026748','7316034738','7316033496','7310007738','7310004201','7310018123','7310019826','7310003534','7310013123','7310032496','7310031534','7180002414','7180002206','7180002462','6419002486','7609011330','7609009123','7609007534','7609063123','7609086451','7609056123','7609082123','7609054123','7609095123','7609094123','7609098123','7609135123','7609136123','7609146123','7609141366','7609147123','7609148123','7609102330','7609131201','7609143366','7609132826','7609277499','7609295330','7609278499','7609215123','7609354123','7609198123','7609194123','7609010147','7609173123','7609205123','7609012932','7609211123','7609010534','7609190123','7608019366','7608006123','7406018122','7406008340','7406001328','7406013738','7406024123','7406029123','7406038496','7406007123','7406034330','7406025123','7407008340','7407001451','7407015123','7407012123','7410007451','7410008330','7410004340','7410012451','7326006147','7318002123','7205006414','7173007201','7173004420','7173008201','7173003831','7175001737','7175003201','7104012486','7104013201','7104022201','7104020201','7104021201','7104033201','7106021201','7107010829','7162001201','7162001831','7165003201','7120007428','7120004428','7120006414','7129021414','7129019428','7177003408','7129011414','7120012428','7130034414','7177012414','7120011414','7129022414','7120015428','7120013428','7177011428','7177009414','7177008206','7120002408','7618002748','7379027136','7316053930','7609352748','7609367738','7610039738','7609356365','7609358123','7609357123','5173002486','7316007123','7617001461','7609008330','7609189123','7608008738','5407020754','7609013451','7406015123','7226003414','7406001123','7609092123','6609022665','7410023123','7609013330','7119001428','7326009330','7177006206','5609004123','7609052123','5180001414','7609039123','7406004451','5609002201','5406059754','7617001748','7406009123','7316008201','7379013201','7379010738');
        
        if(in_array($bn, $filter_goods_bn_arr)){
            array_shift($images);
        }
    }

}
